package seismosurfer.servlets.util;

import java.io.Serializable;

import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/** 
 * This class is a listener for both session creation and destruction, and for
 * session activation and passivation. It must be configured via your web
 * application's <code>web.xml</code> deployment descriptor as follows for the
 * container to call it:
 * 
 * <blockquote><code><pre>
 *   &lt;listener&gt;
 *     &lt;listener-class&gt;
 *       seismosurfer.servlets.util.SessionListener
 *     &lt;/listener-class&gt;
 *   &lt;/listener&gt;
 * </pre></code></blockquote>
 * 
 * <code>&lt;listener&gt;</code> elemements can occur between
 * <code>&lt;context-param&gt;</code> and <code>&lt;servlet&gt;</code>
 * elements in your deployment descriptor.
 * 
 * The {@link #sessionCreated(HttpSessionEvent)} callback will automatically add
 * an instance of this listener to any newly created <code>HttpSession</code>
 * for detection of session passivation and re-activation.
 * 
 * Borrowed from Turbine.
 * 
 * @see javax.servlet.http.HttpSessionListener
 */
public class SessionListener implements HttpSessionListener,
        HttpSessionActivationListener, Serializable {

    // ---- HttpSessionListener implementation -----------------------------
    
    private static final long serialVersionUID = 7089611889384132934L;

    /**
     * Called by the servlet container when a new session is created
     * 
     * @param event
     *            Session creation event.
     */
    public void sessionCreated(HttpSessionEvent event) {
        SessionHandler.addSession(event.getSession());
    }

    /**
     * Called by the servlet container when a session is destroyed
     * 
     * @param event
     *            Session destruction event.
     */
    public void sessionDestroyed(HttpSessionEvent event) {
        SessionHandler.removeSession(event.getSession());
    }

    // ---- HttpSessionActivationListener implementation -------------------

    /**
     * Called by the servlet container when an existing session is
     * (re-)activated.
     * 
     * @param event
     *            Session activation event.
     */
    public void sessionDidActivate(HttpSessionEvent event) {
        SessionHandler.addSession(event.getSession());
    }

    /**
     * Called by the servlet container when a an existing session is passivated.
     * 
     * @param event
     *            Session passivation event.
     */
    public void sessionWillPassivate(HttpSessionEvent event) {
        SessionHandler.removeSession(event.getSession());
    }
}